import axios from 'axios'
// import { ElMessage } from 'element-plus'
import type { ApiResponse, HttpMethod } from '@/types/global'
import { da } from 'element-plus/es/locales.mjs'
const instance = axios.create({
    baseURL: import.meta.env.VITE_API_HOST,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
instance.interceptors.request.use((config) => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
})

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        const { data } = response
        if (data.code === 0) {
            return data
        }
        if (data.code === 401) {
            ElMessage.error('登录失效，请重新登录')
            localStorage.clear()
            setTimeout(() => {
                location.href = '/login'
            }, 1000)
            return
        } else {
            ElMessage.error(data.msg)
            return Promise.reject(data)
        }
    },
    (error) => {
        if (!error.response) {
            ElMessage.error('请求超时~')
            return
        }
        let message = ''
        const { status } = error.response
        switch (status) {
            case 401:
                message = '需要重新登录'
                break
            case 500:
                message = '服务器错误'
                break
            default:
                message = error.response.statusText
        }
        ElMessage.error(message)
        if (status === 401) {
            localStorage.clear()
        }
        return Promise.reject(error)
    }
)

export const request = <T = any>(url: string, params: any, method: HttpMethod): Promise<ApiResponse<T>> => {
    const options = {
        url,
        method: method.toUpperCase(),
        params: {},
        data: {}
    }
    switch (options.method) {
        case 'GET':
            if ('id' in params) {
                options.url += '/' + params.id
            } else {
                options.params = params
            }
            break
        case 'POST':
            options.data = params
            break
        case 'PUT':
            if ('id' in params) {
                options.url += '/' + params.id
            }
            options.data = params
            break
        case 'DELETE':
            if ('id' in params) {
                options.url += '/' + params.id
            }
            break
    }
    return instance.request(options)
}
